package com.westar.base.businessUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.westar.core.conf.SysConst;
import com.westar.base.pojo.WestarResult;
import com.westar.base.util.CustomFilePart;
import com.westar.base.util.JsoupSelfUtil;
import com.westar.base.util.WestarHttpUtil;
import org.apache.commons.httpclient.methods.multipart.ByteArrayPartSource;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.net.URLDecoder;
import java.util.*;

/**
 * 办件录入相关操作
 */
public class EditAffairUtil {

    private static Logger logger = LoggerFactory.getLogger( EditAffairUtil.class);

    /**
     * 自动受理数据，仅用于保存草稿和第一次受理
     * @param actCookie 当前操作人员的认证信息
     * @param document 数据页面
     * @param result
     * @param saveType 保存类型
     * @param id 办件主键 0 标识暂存的 非0标识
     * @return
     * @throws IOException
     */
    public static WestarResult affairEdit(String actCookie, Document document,
                                          Map<String, String> result,String saveType,String id) throws IOException {
        //已经存在的隐藏数据
        Elements formDataExists = document.select("#data_div");

        if(saveType.equals( "4" ) ) { //提交才验证
            //提交办件信息
            String resStr = EditAffairUtil.saveAffair(actCookie,result);
            JSONObject jsonObject = JSONObject.parseObject(resStr);
            boolean success = jsonObject.getBoolean("success");
            if(success){
                String affairId = jsonObject.getString( "id" );
                String appendixSource = formDataExists.select( "#appendixSource" ).attr( "value" );
                //是否统一受理 1.统一受理 2.非统一受理 3.全程办理
                if(StringUtils.isNotEmpty( appendixSource ) && appendixSource.equals( "1" )){

                    //开始流程
                    String responeBody = EditAffairUtil.startProcess(actCookie,affairId,"false");
                    jsonObject = JSONObject.parseObject(responeBody);
                    success = jsonObject.getBoolean("success");
                    if(success){
                        String wfInstanceId = jsonObject.getString("procInstId" );

                        Map<String,String> formparam = new HashMap<String,String>(2 );
                        formparam.put("wfInstanceId",wfInstanceId);

                        responeBody = EditAffairUtil.handle(actCookie,"4", id,formparam);
                        jsonObject = JSONObject.parseObject(responeBody);
                        if(jsonObject.getBoolean( "success" )){
                            return WestarResult.build(0,"success","");
                        }else{
                            return WestarResult.build(-1,"error","提交表单失败！");
                        }
                    }else{
                        return WestarResult.build(-1,"error","提交表单失败！");
                    }
                }else{
                    return EditAffairUtil.submit(actCookie,document,null);
                }
            }else{
                return WestarResult.build(-1,"error","提交表单失败！");
            }
//        }else if(saveType.equals( "5" ) ) { //提交才验证
//            //TODO 提交才验证
        }else{
            String resStr = EditAffairUtil.saveAffair(actCookie,result);

            JSONObject jsonObject = JSONObject.parseObject(resStr);
            boolean success = jsonObject.getBoolean("success");
            if(success){
                String affairId = jsonObject.getString( "id" );
                return WestarResult.build(0,"success",affairId);
            }else{
                return WestarResult.build(-1,"error","提交表单失败！");
            }
        }
    }

    private static WestarResult submit(String actCookie, Document document, String submitType) throws IOException {
        //已经存在的隐藏数据
        Elements formDataExists = document.select("#data_div");
        //构建提交表单的数据
        Map<String,String> formParam = EditAffairUtil.constrFormForSubmit(document,submitType);
        //返回的结果
        String res = WorkflowUtil.createAndStartUpProcess(actCookie,formParam);

        JSONObject resJson = JSONObject.parseObject( res);
        String procInstId  = resJson.getString("procInstId");

        String id = formDataExists.select( "#id" ).attr( "value" );
        Map<String,String> formHandleparam = new HashMap<>( );
        formHandleparam.put( "wfInstanceId",procInstId );

        String responeBody =  EditAffairUtil.handle( actCookie,"4",id ,formHandleparam);
        JSONObject jsonObject = JSONObject.parseObject(responeBody);
        if(jsonObject.getBoolean( "success" )){
            return WestarResult.build(0,"success","");
        }else{
            return WestarResult.build(-1,"error","提交表单失败！");
        }
    }

    public static Map<String, String> constrFormForSubmit(Document document,String submitType) {
        //已经存在的隐藏数据
        Elements formDataExists = document.select("#data_div");
        //需要解析的数据
        Elements formDatas = document.select("#cc");

        Map<String, String> result = new HashMap<>( );

        String busiId = formDataExists.select( "#id" ).attr( "value" );
        String busiAlias = "COMMON-MODEL";
        String isFitstNodeAutoSubmit = (StringUtils.isNotEmpty( submitType ) && submitType.equals( "1" ))?"true":"false";

        String totalDue = formDatas.select( "#promiseTimeLimit" ).attr( "value" );

        Map<String,String> obtain = EditAffairUtil.obtainValueForSubmit(document);

        String procDefKey = formDataExists.select( "#wfTemplateKey" ).attr( "value" );
        String shardKey = formDataExists.select( "#shardKey" ).attr( "value" );
        String busiTitle = formDatas.select( "#eventName" ).attr( "value" );
        String busiCode = formDatas.select( "#affairCode" ).attr( "value" );
        String BIZ_PROP_DO_CASE_TYPE = "1"; // 当流程上没有配置人的时候，通过这个标志，为固定角色产生待办任务：1-依申请、2-主动行使
        String deptCode = formDataExists.select( "#createDeptCode" ).attr( "value" );
        String busiDeptCode = formDataExists.select( "#performDeptCode" ).attr( "value" );
        String busiDeptName = formDataExists.select( "#performDeptCode" ).attr( "value" );
        String affairCode = busiCode;
        String eventType = formDataExists.select( "#eventType" ).attr( "value" );
        String creatorName = formDataExists.select( "#creatorName" ).attr( "value" );
        String applicantName = obtain.get("applicantName");
        String eventName = busiTitle;
        String isParallel = formDataExists.select( "#isParallel" ).attr( "value" );
        String isMultilevel = formDataExists.select( "#isMultilevel" ).attr( "value" );
        String limitType = formDataExists.select( "#daysType" ).attr( "value" );
        String legalTimeLimit = formDatas.select( "#legalTimeLimit" ).attr( "value" );
        String applyType = formDataExists.select( "#applyType" ).attr( "value" );
        String applicantIdCard = obtain.get("applicantIdCard");
        String affairParallelCode = formDataExists.select( "#affairParallelCode" ).attr( "value" );
        String isJointTrail = formDataExists.select( "#isJointTrail" ).attr( "value" );
        String jointTrailCode = formDataExists.select( "#jointTrailCode" ).attr( "value" );
        String projectCode = formDatas.select( "#projectcode" ).attr( "value" );
        String projectName = formDataExists.select( "#projectname" ).attr( "value" );

        //1：现场取件，2：物流
        Elements pickupTypeRadio = formDatas.select("input[name='pickupType']");
        String pickupType = JsoupSelfUtil.getRadioVal(pickupTypeRadio);

        // 事项区域编码
        String areaCode = formDataExists.select( "#implAreaCode" ).attr( "value" );
        // 事项编码
        String eventCode = formDataExists.select( "#eventCode" ).attr( "value" );
        // 是否统一受理： 1.统一受理 2.非统一受理 3.全程办理
        String appendixSource = formDataExists.select( "#appendixSource" ).attr( "value" );
        // 一级部门编码
        String firstDeptCode = formDataExists.select( "#firstDeptCode" ).attr( "value" );
        // 一级部门名称
        String firstDeptName = formDataExists.select( "#firstDeptName" ).attr( "value" );
        // 一级部门排序
        String firstDeptSortKey = formDataExists.select( "#firstDeptSortKey" ).attr( "value" );
        // 办件类型，1：即办件、2：承诺件
        String appoveTimeLimit = formDataExists.select( "#appoveTimeLimit_1" ).attr( "value" );

        result.put( "busiId",busiId );
        result.put( "busiAlias",busiAlias );
        result.put( "isFitstNodeAutoSubmit", isFitstNodeAutoSubmit);
        result.put( "totalDue", totalDue);
        result.put( "procDefKey",procDefKey );
        result.put( "shardKey",shardKey );
        result.put( "busiTitle",busiTitle );
        result.put( "busiCode", busiCode);
        result.put( "BIZ_PROP_DO_CASE_TYPE",BIZ_PROP_DO_CASE_TYPE );
        result.put( "deptCode", deptCode);
        result.put( "busiDeptCode",busiDeptCode );
        result.put( "busiDeptName",busiDeptName );
        result.put( "affairCode",affairCode );
        result.put( "eventType",eventType );
        result.put( "creatorName",creatorName );
        result.put( "applicantName",applicantName );
        result.put( "eventName",eventName );
        result.put( "isParallel",isParallel );
        result.put( "isMultilevel",isMultilevel );
        result.put( "limitType",limitType );
        result.put( "legalTimeLimit",legalTimeLimit );
        result.put( "applyType",applyType );
        result.put( "applicantIdCard",applicantIdCard );
        result.put( "affairParallelCode",affairParallelCode );
        result.put( "isJointTrail",isJointTrail );
        result.put( "jointTrailCode",jointTrailCode );
        result.put( "projectCode",projectCode );
        result.put( "projectName",projectName );
        result.put( "pickupType",pickupType );
        result.put( "areaCode", areaCode);
        result.put( "eventCode",eventCode );
        result.put( "appendixSource", appendixSource);
        result.put( "firstDeptCode", firstDeptCode);
        result.put( "firstDeptName",firstDeptName );
        result.put( "firstDeptSortKey", firstDeptSortKey);
        result.put( "appoveTimeLimit", appoveTimeLimit);

        //综合窗口进驻事项权限
        String rights = formDataExists.select( "#rights" ).attr( "value" );
        String busiType = formDataExists.select( "#busiType" ).attr( "value" );
        // 综窗办件_取件窗口,多个综窗以逗号[,]隔开
        String currentUserBigDeptCode = formDataExists.select( "#currentUserBigDeptCode" ).attr( "value" );

        boolean state = StringUtils.isNotEmpty(busiType) // 综窗
                && busiType.equals( "2" )
                &&StringUtils.isNotEmpty(rights);
        if(state){
            // 是否综窗办件:1-是,空活0-否
            result.put( "ZCBJ_PARAM_IS_ZCBJ", "1");
            result.put( "ZCBJ_PARAM_DEPTCODE", currentUserBigDeptCode);
            // 综窗办件_取件窗口,多个综窗以逗号[,]隔开
            result.put( "ZCBJ_BUSI_TYPE", rights);
        }

        //便民服务中心，增加传的参数
        String isConvenienceCenter = formDataExists.select( "#isConvenienceCenter" ).attr( "value" );

        String authorizationStr = null;

        //TODO  乡村授权 节点任务由谁认领json
        String authorization = null;
        if(StringUtils.isNotEmpty(authorizationStr)){
            authorization = authorizationStr;
        }

        //判断是不是便民服务中心
        if(isConvenienceCenter.equals( "true" )){
            if(StringUtils.isEmpty(submitType) || !submitType.equals( "10" )){
                result.put( "BMZX_PARAM_IS_BMZX", "1");
                result.put( "BMZX_PARAM_DEPTCODE", currentUserBigDeptCode);
                result.put( "AUTHORIZATION_DEPT_ROLE", authorization);
            }
        }
        return result;

    }

    /**
     * 开始流程
     * @param actCookie 当前操作人员的认证信息
     * @param affairId 办件主键
     * @param saveType 是否为第一个节点的自动提交
     * @return
     * @throws IOException
     */
    private static String startProcess(String actCookie, String affairId, String saveType) throws IOException {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/startProcess";
        Map<String,String> formParam = new HashMap<String,String>(2 );
        formParam.put( "affairId",affairId );
        formParam.put( "isFitstNodeAutoSubmit",saveType );
        String responeBody = WestarHttpUtil.postMethod(url,actCookie,formParam);
        return responeBody;
    }


    public static Map<String,String> obtainValueForSave(Map<String,String> allParam){
        Map<String,String> result = new HashMap<String,String>();
        //1.企业法人 2.自然人 3.其他组织 4.事业法人5.社会组织法人 6.行政机关 7.非法人企业
        String applicantType = allParam.getOrDefault("applicantType","1");
        if(applicantType.equals( "2" )){
            List<String> keys = new ArrayList<>();
            //姓名
            keys.add("applicantName");
            //证件类型
            //113.户口簿
            //413.公务普通护照
            //418.外国人旅行证
            //118.中国人民解放军士兵证
            //792.境外人员身份证明
            //111.居民身份证
            //411.外交护照
            //511.台湾居民来往大陆通行证
            //117.出生医学证明
            //516.港澳居民来往内地通行证
            //553.外国人永久居留身份证
            //115.中国人民武装警察部队警官证
            //415.旅行证
            //114.中国人民解放军军官证
            //119.中国人民武装警察部队士兵证
            //791.外交人员身份证明
            //112.临时居民身份证
            //412.公务护照
            //555.外国人临时居留证
            //554.外国人居留证或居留许可
            //154.居住证
            //414.普通护照
            //120.中国人民解放军文职人员证
            //122.中国人民武装警察部队文职人员证
            keys.add("cardType");
            //1.男 2女
            keys.add("applicantSex");
            //证件号码
            keys.add("applicantIdCard");
            //联系电话
            keys.add("applicantPhone");
            //电子邮件
            keys.add("applicantEmail");
            //通讯地址
            keys.add("applicantAddress");
            //邮政编码
            keys.add("applicantPostalCode");
            //照片
            keys.add("applicantPhotoId");
            for (String key:  keys) {
                String val = allParam.getOrDefault(key,"");
                result.put( key, val);
            }
        }else{
            List<String> keys = new ArrayList<>();
            //主体性质
            //1.国家行政机关
            //2.事业单位
            //3.企业
            //4.其它
            keys.add("mainProperty");
            //证件类型
            //999.其他
            //1.统一社会信用代码
            //2.组织机构代码
            //3.工商登记号（营业执照）
            //4.事业单位法人证书
            //5.社会团体法人登记证书
            //830.律师事务所执业许可证
            //821.营业执照
            //6.党政机关法人（无证书）
            //813.驻华机构证明
            //99.其他法人或其他组织有效证件
            keys.add("cardType");
            //证件号码
            keys.add("applicantIdCard");
            //机构名称
            keys.add("applicantName");
            //法定代表人
            keys.add("legalPerson");
            //机构地址
            keys.add("applicantAddress");
            //邮政编码
            keys.add("applicantPostalCode");
            //通讯地址
            keys.add("applicantPostalAddress");
            //电子邮件
            keys.add("applicantEmail");
            //联系电话
            keys.add("applicantPhone");
            //说明
            keys.add("explains");
            //法定代表人证件号码
            keys.add("legalpersonIdCard");
            //证件类型
            //113.户口簿
            //413.公务普通护照
            //418.外国人旅行证
            //118.中国人民解放军士兵证
            //792.境外人员身份证明
            //111.居民身份证
            //411.外交护照
            //511.台湾居民来往大陆通行证
            //117.出生医学证明
            //516.港澳居民来往内地通行证
            //553.外国人永久居留身份证
            //115.中国人民武装警察部队警官证
            //415.旅行证
            //114.中国人民解放军军官证
            //119.中国人民武装警察部队士兵证
            //791.外交人员身份证明
            //112.临时居民身份证
            //412.公务护照
            //555.外国人临时居留证
            //554.外国人居留证或居留许可
            //154.居住证
            //414.普通护照
            //120.中国人民解放军文职人员证
            //122.中国人民武装警察部队文职人员证
            keys.add("legalPersonCardType");
            for (String key:  keys) {
                String val = allParam.getOrDefault(key,"");
                result.put( key, val);
            }
        }

        List<String> keys = new ArrayList<>();
        //联系人信息
        //姓名
        keys.add("contactName");
        //性别1 男 2女
        keys.add("contactSex");
        //身份证号码
        keys.add("contactIdCard");
        //证件类型
        keys.add("contactCardType");
        //联系电话
        keys.add("contactPhone");
        //电子邮件
        keys.add("contactEmail");
        //邮政编码
        keys.add("contractPostalCode");
        //通讯地址
        keys.add("contractAddress");
        //备注
        keys.add("remark");
        for (String key:  keys) {
            String val = allParam.getOrDefault(key,"");
            result.put( key, val);
        }
        return result;
    }

    /**
     * 联系人信息用于提交数据的
     * @param document
     * @return
     */
    public static Map<String,String> obtainValueForSubmit(Document document){
        //已经存在的隐藏数据
        Elements formDataExists = document.select("#data_div");
        //1.企业法人 2.自然人 3.其他组织 4.事业法人5.社会组织法人 6.行政机关 7.非法人企业
        Elements recGenderRadio = document.select("input[name='applicantType']");
        String applicantType = JsoupSelfUtil.getRadioVal(recGenderRadio);

        Map<String,String> result = new HashMap<String,String>();
        result.put( "applicantType",applicantType );

        //需要解析的数据
        Elements formDatas = document.select("#cc");
        //自然人信息
        if(applicantType.equals( "2" )){
            String applicantName = formDatas.select( "#personDiv input[id='applicantName']" ).attr( "value" );

            Elements cardTypeSelect = formDatas.select( "#personDiv select[id='cardType']");
            String cardType =JsoupSelfUtil.getSelectVal(cardTypeSelect);

            Elements applicantSexRadio = formDatas.select("#personDiv input[id='applicantSex']");
            String applicantSex = JsoupSelfUtil.getRadioVal(applicantSexRadio);

            String applicantIdCard = formDatas.select( "#personDiv input[id='applicantIdCard']" ).attr( "value" );
            String applicantPhone = formDatas.select( "#personDiv input[id='applicantPhone']" ).attr( "value" );
            String applicantEmail = formDatas.select( "#personDiv input[id='applicantEmail']" ).attr( "value" );
            String applicantAddress = formDatas.select( "#personDiv input[id='applicantAddress']" ).attr( "value" );
            String applicantPostalCode = formDatas.select( "#personDiv input[id='applicantPostalCode']" ).attr( "value" );
            String applicantPhotoId = formDatas.select( "#personDiv input[id='applicantPhotoId']" ).attr( "value" );

            result.put("applicantName",applicantName );
            result.put("cardType", cardType);
            result.put("applicantSex",applicantSex );
            result.put("applicantIdCard",applicantIdCard );
            result.put("applicantPhone",applicantPhone );
            result.put("applicantEmail",applicantEmail );
            result.put("applicantAddress",applicantAddress );
            result.put("applicantPostalCode",applicantPostalCode );
            result.put("applicantPhotoId",applicantPhotoId );


        }else{
            //法人信息
            Elements mainPropertySelect = formDatas.select( "#LegalOtherDiv select[id='mainProperty']");
            String mainProperty =JsoupSelfUtil.getSelectVal(mainPropertySelect);

            Elements cardTypeSelect = formDatas.select( "#LegalOtherDiv select[id='cardType']");
            String cardType =JsoupSelfUtil.getSelectVal(cardTypeSelect);

            String applicantIdCard = formDatas.select( "#LegalOtherDiv input[id='applicantIdCard']" ).attr( "value" );
            String applicantName = formDatas.select( "#LegalOtherDiv input[id='applicantName']" ).attr( "value" );
            String legalPerson = formDatas.select( "#LegalOtherDiv input[id='legalPerson']" ).attr( "value" );
            String applicantAddress = formDatas.select( "#LegalOtherDiv input[id='applicantAddress']" ).attr( "value" );
            String applicantPostalCode = formDatas.select( "#LegalOtherDiv input[id='applicantPostalCode']" ).attr( "value" );
            String applicantPostalAddress = formDatas.select( "#LegalOtherDiv input[id='applicantPostalAddress']" ).attr( "value" );
            String applicantEmail = formDatas.select( "#LegalOtherDiv input[id='applicantEmail']" ).attr( "value" );
            String applicantPhone = formDatas.select( "#LegalOtherDiv input[id='applicantPhone']" ).attr( "value" );
            String explains = formDatas.select( "#LegalOtherDiv input[id='explains']" ).attr( "value" );
            String legalpersonIdCard = formDatas.select( "#LegalOtherDiv input[id='legalpersonIdCard']" ).attr( "value" );

            Elements legalPersonCardTypeSelect = formDatas.select( "#LegalOtherDiv select[id='legalPersonCardType']");
            String legalPersonCardType =JsoupSelfUtil.getSelectVal(legalPersonCardTypeSelect);

            result.put("mainProperty",mainProperty );
            result.put("cardType",cardType );
            result.put("applicantIdCard",applicantIdCard);
            result.put("applicantName", applicantName);
            result.put("legalPerson", legalPerson);
            result.put("applicantAddress", applicantAddress);
            result.put("applicantPostalCode",applicantPostalCode );
            result.put("applicantPostalAddress", applicantPostalAddress);
            result.put("applicantEmail", applicantEmail);
            result.put("applicantPhone", applicantPhone);
            result.put("explains", explains);
            result.put("legalpersonIdCard", legalpersonIdCard);
            result.put("legalPersonCardType", legalPersonCardType);
        }

        String contactName = formDatas.select( "#appliDiv input[id='contactName']" ).attr( "value" );

        Elements contactSexRadio = formDatas.select("#appliDiv input[id='contactSex']");
        String contactSex = JsoupSelfUtil.getRadioVal(contactSexRadio);

        Elements contactCardTypeSelect = formDatas.select( "#appliDiv select[id='contactCardType']");
        String contactCardType =JsoupSelfUtil.getSelectVal(contactCardTypeSelect);

        String contactIdCard = formDatas.select( "#appliDiv input[id='contactIdCard']" ).attr( "value" );
        String contactPhone = formDatas.select( "#appliDiv input[id='contactPhone']" ).attr( "value" );
        String contactEmail = formDatas.select( "#appliDiv input[id='contactEmail']" ).attr( "value" );
        String contractPostalCode = formDatas.select( "#appliDiv input[id='contractPostalCode']" ).attr( "value" );
        String contractAddress = formDatas.select( "#appliDiv input[id='contractAddress']" ).attr( "value" );
        String remark = formDatas.select( "#appliDiv input[id='remark']" ).attr( "value" );

        result.put("contactName",contactName );
        result.put("contactSex", contactSex);
        result.put("contactCardType",contactCardType );
        result.put("contactIdCard",contactIdCard );
        result.put("contactPhone", contactPhone);
        result.put("contactEmail",contactEmail );
        result.put("contractPostalCode",contractPostalCode );
        result.put("contractAddress", contractAddress);
        result.put("remark", remark);

        return result;
    }
    public static Map<String,String> constrFormForSave(Document document,String saveType){
        //修改获取数据的div
        Elements formDataExists = document.select("#data_div");
        //需要解析的数据
        Elements formDatas = document.select("#cc");

        Map<String,String> param = new HashMap<>(  );
        String id = formDataExists.select( "#id" ).attr( "value" );
        String ilWfTemplateId = formDataExists.select( "#ilWfTemplateId" ).attr( "value" );
        String shardKey = formDataExists.select( "#shardKey" ).attr( "value" );

        String templetId = formDataExists.select( "#templetId" ).attr( "value" );
        String nodeId = formDataExists.select( "#nodeId" ).attr( "value" );
        String esheetId = formDataExists.select( "#esheetId" ).attr( "value" );
        String implListId = formDataExists.select( "#implListId" ).attr( "value" );
        String applyType = formDataExists.select( "#applyType" ).attr( "value" );
        String busiType = formDataExists.select( "#busiType" ).attr( "value" );
        String affairSteamId = formDataExists.select( "#affairSteamId" ).attr( "value" );
        String taskId = formDataExists.select( "#taskId" ).attr( "value" );
        String nodeType = formDataExists.select( "#nodeType" ).attr( "value" );
        String nodeName = formDataExists.select( "#nodeName" ).attr( "value" );
        String affariLogisticalId = formDataExists.select( "#affariLogisticalId" ).attr( "value" );

        Elements isProjectRadio = formDatas.select("input[name='isProject']");
        String isProject = JsoupSelfUtil.getRadioVal(isProjectRadio);

        Elements pickupTypeRadio = formDatas.select("input[name='pickupType']");
        String pickupType = JsoupSelfUtil.getRadioVal(pickupTypeRadio);

        String eventName = formDatas.select( "#eventName" ).attr( "value" );
        String affairName = formDatas.select( "#affairName" ).attr( "value" );



        String recName = formDatas.select( "#pickInfo input[name='recName']" ).attr( "value" );
        String recPhone = formDatas.select( "#pickInfo input[name='recPhone']" ).attr( "value" );

        String recAddrProvince = formDatas.select( "#recAddrProvince" ).attr( "value" );
        String recAddrCity = formDatas.select( "#recAddrCity" ).attr( "value" );
        String recAddrCounty = formDatas.select( "#recAddrCounty" ).attr( "value" );
        String postalCode = formDatas.select( "#pickInfo input[name='postalCode']" ).attr( "value" );
        String recAddress = formDatas.select( "#pickInfo input[name='recAddress']" ).attr( "value" );
        String applyNum = formDatas.select( "#applyNum" ).attr( "value" );
        String consulationContent = formDatas.select( "#consulationContent" ).attr( "value" );
        String replyContent = formDatas.select( "#replyContent" ).attr( "value" );
        String packageValue = formDatas.select( "#tb" ).attr( "value" );

        Elements isImplPackageRadio = formDatas.select("input[name='isImplPackage']");
        String isImplPackage = JsoupSelfUtil.getRadioVal(isImplPackageRadio);

        param.put( "id",id );
        param.put( "ilWfTemplateId",ilWfTemplateId );
        param.put( "affairName", affairName );
        param.put( "shardKey", shardKey);
        param.put( "eventName", eventName);
        param.put( "templetId",templetId );
        param.put( "nodeId",nodeId );
        param.put( "esheetId",esheetId );
        param.put( "saveType", saveType);
        param.put( "implListId",implListId );
        param.put( "applyType",applyType );
        param.put( "busiType", busiType);
        param.put( "affairSteamId",affairSteamId );
        param.put( "taskId", taskId);
        param.put( "nodeType", nodeType);
        param.put( "nodeName",nodeName );
        param.put( "isProject", isProject);
        param.put( "pickupType",pickupType );
        param.put( "affariLogisticalId",affariLogisticalId );
        param.put( "recName",recName );
        param.put( "recPhone",recPhone );
        param.put( "recAddrProvince",recAddrProvince );
        param.put( "recAddrCity",recAddrCity );
        param.put( "recAddrCounty",recAddrCounty );
        param.put( "postalCode", postalCode);
        param.put( "recAddress", recAddress);
        param.put( "applyNum", applyNum);
        param.put( "consulationContent", consulationContent);
        param.put( "replyContent",replyContent );
        param.put( "packageValue", packageValue);
        param.put( "isImplPackage",isImplPackage );

        Map<String,String> obtain = obtainValueForSubmit(document);
        param.putAll(obtain);

        // 投资项目的表单F
        String projectTempletId = formDataExists.select( "#pesTempletId" ).attr( "value" );
        String projectEsheetId = formDataExists.select( "#pesheetId" ).attr( "value" );
        if(StringUtils.isNotEmpty(isProject) && isProject.equals( "1" )){
            //TODO 获取信息
        }
        if (saveType.equals( "0" )) { // 暂存
            param.put( "logOperType","applyUpdate" ); // 日志操作类型
            param.put("logModel","申请修改"); // 日志事由
        }else if (saveType.equals( "1" )) { // 受理
            param.put( "auditAdvice","1");
            param.put( "auditAdviceName", "受理");
            param.put( "auditRemark", "受理");
        } else if (saveType.equals( "-2" )) {// 不予受理
            param.put("auditAdvice", "0");
            param.put("auditAdviceName", "不予受理");
            param.put("auditRemark", "不予受理");
        }else if(saveType.equals( "3" )){ // 上报
            param.put("logOperType", "applyReport"); // 日志操作类型
            param.put("logModel", "申请上报"); // 日志事由
        }else if(saveType.equals( "4" )){ // 提交
            param.put("auditAdvice", "1");
            param.put("auditAdviceName", "提交");
            param.put("auditRemark", "提交");
            param.put("logOperType", "applySubmit"); // 日志操作类型
            param.put("logModel", "申请提交"); // 日志事由
        }else if(saveType.equals( "5" )){// 提交
            param.put("logOperType", "submitAccept"); // 日志操作类型
            param.put("logModel", "申请提交"); // 日志事由
        }
        return param;
    }


    /**
     * 通过调用接口传递过来的参数
     * @param saveType
     * @param pageInfo
     * @param params
     * @return
     */
    public static Map<String,String> contrFormDataForFirstSave(String saveType,String pageInfo,Map<String,String> params){

        Map<String,String> result = new HashMap<String,String>();

        Document document = Jsoup.parse(pageInfo);
        Elements formDataExists =  document.select("#data_div");
        if(null!= formDataExists && !formDataExists.isEmpty()){
            String id = formDataExists.select( "#id" ).attr( "value" );
            result.put( "id",id );

            String shardKey = formDataExists.select( "#shardKey" ).attr( "value" );
            result.put( "shardKey",shardKey );

            // 流水表相关 -->
            String templetId = formDataExists.select( "#templetId" ).attr( "value" );
            result.put( "templetId",templetId );

            String nodeId = formDataExists.select( "#nodeId" ).attr( "value" );
            result.put( "nodeId",nodeId );

            String affairSteamId = formDataExists.select( "#affairSteamId" ).attr( "value" );
            result.put( "affairSteamId",affairSteamId );

            String taskId = formDataExists.select( "#taskId" ).attr( "value" );
            result.put( "taskId",taskId );

            String nodeType = formDataExists.select( "#nodeType" ).attr( "value" );
            result.put( "nodeType",nodeType );

            String nodeName = formDataExists.select( "#nodeName" ).attr( "value" );
            result.put( "nodeName",nodeName );

            //电子表单相关
            String esheetId = formDataExists.select( "#esheetId" ).attr( "value" );
            result.put( "esheetId",esheetId );

            result.put( "saveType",saveType );


            //事项相关
            String applyType = formDataExists.select( "#applyType" ).attr( "value" );
            result.put( "applyType",applyType );

            //业务类型，1:普通办件；2：综合窗口办件
            String busiType = formDataExists.select( "#busiType" ).attr( "value" );
            result.put( "busiType",busiType );

            //物流（取件）相关
            String affariLogisticalId = formDataExists.select( "#affariLogisticalId" ).attr( "value" );
            result.put( "affariLogisticalId",affariLogisticalId );

        }

        List<String> dataName = new ArrayList<>(  );
        //办件名称
        dataName.add( "affairName" );
        // 投资项目相关 0否 1是
        dataName.add( "isProject" );

        //取件相关	1.现场取件  2.邮寄送达  3.无需取件
        dataName.add( "pickupType" );
        //收件人姓名
        dataName.add( "recName" );
        //联系电话
        dataName.add( "recPhone" );
        //收件地址信息
        dataName.add( "recAddrProvince" );
        dataName.add( "recAddrCity" );
        dataName.add( "recAddrCounty" );
        //邮政编码
        dataName.add( "postalCode" );
        //收件详情地址
        dataName.add( "recAddress" );

        //申请件数
        dataName.add( "applyNum" );

        //咨询内容
        dataName.add( "consulationContent" );
        //答复内容
        dataName.add( "replyContent" );

        //是否项目打包
        dataName.add( "isImplPackage" );
        //打包事项列表
        dataName.add( "packageValue" );

        dataName.add( "ilWfTemplateId" );
        dataName.add( "eventName" );
        dataName.add( "implListId" );
        dataName.add( "applicantType" );

        for (String key:  dataName) {
            String val = params.getOrDefault(key,"");
            result.put( key, val);
            if(key.equals("applyNum") && StringUtils.isNotEmpty(val)){
                Integer applyNum = Integer.parseInt(val);
                if(applyNum > 1){
                    result.put( "applyNumRemark", "说明");
                }else{
                    result.put( "applyNumRemark", "");
                }
            }
        }
        //TODO 默认不是投资项目
        result.put( "isProject", "0");
        Map<String,String> obtain = EditAffairUtil.obtainValueForSave(params);
        result.putAll( obtain);

        //TODO 投资项目的表单F

        if (saveType.equals( "0" )) { // 暂存
            result.put( "logOperType","applyUpdate" ); // 日志操作类型
            result.put("logModel","申请修改"); // 日志事由
        }else if (saveType.equals( "1" )) { // 受理
            result.put( "auditAdvice","1");
            result.put( "auditAdviceName", "受理");
            result.put( "auditRemark", "受理");
        } else if (saveType.equals( "-2" )) {// 不予受理
            result.put("auditAdvice", "0");
            result.put("auditAdviceName", "不予受理");
            result.put("auditRemark", "不予受理");
        }else if(saveType.equals( "3" )){ // 上报
            result.put("logOperType", "applyReport"); // 日志操作类型
            result.put("logModel", "申请上报"); // 日志事由
        }else if(saveType.equals( "4" )){ // 提交
            result.put("auditAdvice", "1");
            result.put("auditAdviceName", "提交");
            result.put("auditRemark", "提交");
            result.put("logOperType", "applySubmit"); // 日志操作类型
            result.put("logModel", "申请提交"); // 日志事由
        }else if(saveType.equals( "5" )){// 提交
            result.put("logOperType", "submitAccept"); // 日志操作类型
            result.put("logModel", "申请提交"); // 日志事由
        }
        return result;

    }


    /**
     *
     * @param actCookie
     * @param type type 1:已受理、-1：待补正补齐、-2：不予受理、0：已补正补齐、3: 便民中心上报、4：提交
     * @param id
     * @param formparam
     * @throws IOException
     */
    private static String handle(String actCookie ,String type, String id,Map<String,String> formparam) throws IOException {
        String url =  "http://"+SysConst.DOMAIN +"/dothingsui/affair/handle/" + id + "/" + type;
        String responeBody = WestarHttpUtil.postMethod(url,actCookie,formparam);
        return responeBody;


    }


    /**
     * 应交材料 全部符合受理标准
     * @param affairId
     * @param pageInfo
     * @param actCookie
     * @throws Exception
     */
    public static void initMaterial(String affairId, String pageInfo,
                                    String actCookie,String itemName,String filebasePath) throws Exception {
        Document document = Jsoup.parse(pageInfo);
        //数据存在的DIV
        Elements formDataExists = document.select("#data_div");
        //状态
        String status = formDataExists.select( "#status" ).attr( "value" );
        if(status.equals( "0" ) || status.equals( "10" )){
            if(StringUtils.isEmpty(itemName) || !itemName.equals("suining")){
                String version = formDataExists.select( "#version" ).attr( "value" );

                Elements formDatas = document.select("#cc");
                String affairCode = formDatas.select( "#affairCode" ).attr( "value" );

                //查询所有材料信息
                List<JSONObject> listAffairMaterial = EditAffairUtil.listAffairMaterial(actCookie,affairId);
                if(null!= listAffairMaterial && !listAffairMaterial.isEmpty()){

                    Map<String,String> obtain = EditAffairUtil.obtainValueForSubmit(document);

                    for (int index = 0,len = listAffairMaterial.size();index < len;index++) {
                        JSONObject row = listAffairMaterial.get( index );
                        String idForStr = row.getString("idForStr");
                        String materialName = row.getString("materialName");
                        //资料上传
                        EditAffairUtil.showUploadMaterial(actCookie,affairId,idForStr,materialName,obtain,affairCode,filebasePath,version);
                    }
                }
            }
            String url = "http://"+ SysConst.DOMAIN+"/affairMaterial/auditResultAll/"+affairId;
            String responeBody = WestarHttpUtil.getMethod(url,actCookie,null);
        }
    }


    /**
     * 提交办件信息
     * @param actCookie
     * @param searchParam
     * @return
     * @throws IOException
     */
    public static String saveAffair(String actCookie,Map<String, String> searchParam) throws IOException {
        Map<String,String> result = new HashMap<String,String>(  );
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/save";
        String responeBody = WestarHttpUtil.postMethod(url,actCookie,searchParam);
        return responeBody;
    }

    /**
     * 办理
     * @param actCookie
     * @param id
     * @param busiType
     * @param applyType
     * @return
     * @throws Exception
     */
    public static String affairEditRespone(String actCookie,String id,String busiType,String applyType)
            throws IOException {
        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/affair/edit/"+id;
        Map<String,String> searchParam = new HashMap<String,String>();
        if(StringUtils.isNotEmpty(busiType  )){
            searchParam.put( "busiType",busiType);
        }
        if(StringUtils.isNotEmpty( applyType )){
            searchParam.put( "applyType",applyType);
        }
        String responeBody = WestarHttpUtil.getMethod(url,actCookie,searchParam);
        return responeBody;
    }

    /**
     * 验证是否正确
     * @param actcookie
     * @param eventName
     * @param id
     * @return
     * @throws IOException
     */
    public static boolean checkImplementDetail(String actcookie, String eventName, String id) throws IOException{
        Map<String,String> result = new HashMap<String,String>(  );
        String url = "http://"+SysConst.DOMAIN+"/dothingsui/implementList/selectImplementTree";
        Map<String, String> searchParam = new HashMap<String,String>( );
        searchParam.put( "busiType","1");
        searchParam.put( "applyType","0");
        searchParam.put( "implListId","");
        searchParam.put( "eventName",eventName);
        if(StringUtils.isNotEmpty( id )){
            searchParam.put( "id",id.toString());
        }
        String responeBody = WestarHttpUtil.postMethod(url,actcookie,searchParam);
        if(StringUtils.isEmpty(responeBody)){
            return false;
        }
        JSONArray jsonArray = JSONArray.parseArray(responeBody);
        if(jsonArray.size() == 0){
            return false;
        }
        JSONObject jsonObject = jsonArray.getJSONObject( 0 );
        String eventId = jsonObject.getString( "id" );
        String state = jsonObject.getString( "state" );
        if(state.equals( "closed" )){
            return checkImplementDetail(actcookie,eventName,eventId);
        }else{
            return true;
        }
    }

//    /**
//     * 查询数形结构的文件
//     * @param actcookie
//     * @param searchParam
//     * @return
//     * @throws IOException
//     */
//    public static Map<String,String> selectImplementTree(String actcookie, Map<String, String> searchParamV1) throws IOException {
//
//        Map<String,String> result = new HashMap<String,String>(  );
//        String url = "http://"+SysConst.DOMAIN+"/implementList/selectImplementTree";
//        String responeBody = WestarHttpUtil.postMethod(url,actcookie,searchParamV1);
//
//        JSONArray jsonArray = JSONArray.parseArray(responeBody);
//        JSONObject jsonObject = jsonArray.getJSONObject( 0 );
//        JSONObject attributes = jsonObject.getJSONObject("attributes");
//
//        String appoveObject = attributes.getString("appoveObject" );
//        String eventName = attributes.getString("eventName" );
//        String promiseTimeLimit = attributes.getString("promiseTimeLimit" );
//        String legalTimeLimit = attributes.getString("legalTimeLimit" );
//        String majorTerm = attributes.getString("majorTerm" );
//        String implListId = attributes.getString("idForStr" );
//
//        result.put( "appoveObject",appoveObject );
//        result.put( "eventName",eventName );
//        result.put( "promiseTimeLimit",promiseTimeLimit );
//        result.put( "legalTimeLimit",legalTimeLimit );
//        result.put( "majorTerm",majorTerm );
//        result.put( "implListId",implListId );
//
//
//
//        Map<String,String> searchParam = new HashMap<>();
//        searchParam.put( "implListId",implListId);
//        searchParam.put( "implWfStatus","2");
//        Map<String,String> queryAndValidWfTemplate = EditAffairUtil.queryAndValidWfTemplate(token,searchParam,"1");
//        result.putAll(queryAndValidWfTemplate);
//
//        return result;
//    }

    /**
     * 查询并校验模板
     * @param actCookie
     * @param searchParam
     * @return
     * @throws IOException
     */
    public static Map<String, String> queryAndValidWfTemplate(String actCookie, Map<String, String> searchParam,String isValidWf)
            throws IOException {
        Map<String, String> result = new HashMap<String, String>();

        String url = "http://"+ SysConst.DOMAIN+"/dothingsui/implementList/queryWfTemplate4Affair";
        String responeBody = WestarHttpUtil.postMethod(url,actCookie,searchParam);

        String rows = JSONObject.parseObject(responeBody).getString("rows"  );
        JSONArray jsonArray = JSONArray.parseArray(rows);

        if(null!=jsonArray && !jsonArray.isEmpty()){

            JSONObject jsonObject = jsonArray.getJSONObject( 0 );

            String ilWfTemplateId = jsonObject.getString("idForStr");
            String procDefName = jsonObject.getString("wfTemplateName");


            if(StringUtils.isNotEmpty(isValidWf) && isValidWf.equals( "1")){
                String wfTemplateKey = jsonObject.getString("wfTemplateKey");
                String responeValidBody = WorkflowUtil.validDefByKey(actCookie,wfTemplateKey);
                JSONObject responeValidObject = JSONObject.parseObject(responeValidBody);
                String wfProcDefValid = responeValidObject.getString( "wfProcDefValid" );

                if(StringUtils.isNotEmpty(wfProcDefValid)){
                    String status = JSONObject.parseObject(wfProcDefValid).getString("status");
                    String isValid = JSONObject.parseObject(wfProcDefValid).getString("isValid");
                    if(StringUtils.isNotEmpty( status ) && !status.equals( "2" )
                    && StringUtils.isNotEmpty(isValid ) && isValid.equals( "0" )){
                        return null;
                    }else{
                        result.put( "ilWfTemplateId",ilWfTemplateId);
                        result.put( "procDefName",procDefName);
                    }
                }else{
                    result.put( "ilWfTemplateId",ilWfTemplateId);
                    result.put( "procDefName",procDefName);
                }

            }else{
                result.put( "ilWfTemplateId",ilWfTemplateId);
                result.put( "procDefName",procDefName);
            }

        }
        return result;
    }

    /**
     * 构建照片信息
     * @param actCookie 表单数据
     * @param pageInfo 表单数据
     * @param multiValueMap 页面文件数据
     * @param params 页面普通表单数据
     * @return
     */
    public static String constrApplicantPhotoId(String actCookie,
                                                String pageInfo,
                                                MultiValueMap<String, MultipartFile> multiValueMap,
                                                Map<String,String> params) throws IOException {

        //非自然人才有数据
        String applicantType = params.getOrDefault("applicantType","1");
        if(!applicantType.equals( "2" )){
            return null;
        }

        if(null == multiValueMap || multiValueMap.isEmpty()){
            return null;
        }

        List<MultipartFile> fileList = multiValueMap.get("uploadedfileOne");
        if(null == fileList || fileList.isEmpty()){
            return null;
        }

        MultipartFile file = fileList.get(0);
        Document doc = Jsoup.parse(pageInfo);
        Elements eleForm = doc.select("#cc");
        Elements formDatas = eleForm.select( "div[title='基本信息']" );
        if(null == formDatas || formDatas.isEmpty()){
            return null;
        }

        String busiId = formDatas.select( "#id" ).attr( "value" );
        String areaCode = formDatas.select( "#shardKey" ).attr( "value" );



        String url = "http://"+SysConst.DOMAIN+"/attachment/importMultiFile";
        Map<String,String> postParam = new HashMap<String,String>();
        postParam.put( "busiId",busiId );
        postParam.put( "areaCode",areaCode );
        postParam.put( "busiAlias","consulationPhoto" );
        postParam.put( "categoryCode","Affair" );

        InputStream is = file.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len = 0;
        byte[] b = new byte[1024];
        while ((len = is.read(b, 0, b.length)) != -1) {
            baos.write(b, 0, len);
        }
        byte[] buffer =  baos.toByteArray();

        // 文件名
        String fileName = file.getOriginalFilename();
        fileName = URLDecoder.decode(fileName,"UTF-8");

        FilePart filePart = new FilePart("uploadedfileOne", new ByteArrayPartSource(fileName, buffer));
        filePart.setCharSet("utf-8");

        String responeBody = WestarHttpUtil.postMethodWithFile(url,actCookie,postParam,filePart );
        if(StringUtils.isEmpty( responeBody )){
            return null;
        }
        JSONObject jsonObject = JSON.parseObject(responeBody);
        if(jsonObject.getBoolean("success")){
            return jsonObject.getString( "id" );
        }else{
            return null;
        }
    }

    /**
     * 保存材料信息
     * @param multipartFile 页面所有的附件
     * @param affairCode 受理编号
     */
    public static void constrMaterial(MultiValueMap<String, MultipartFile> multipartFile,
                                      String affairCode,String filebasePath) throws IOException {
        if(null == multipartFile || multipartFile.isEmpty()){
            return;
        }

        Iterator<Map.Entry<String,List<MultipartFile>>> itor = multipartFile.entrySet().iterator();
        while (itor.hasNext()){
            Map.Entry<String,List<MultipartFile>> entry = itor.next();
            String fileTag = entry.getKey().toLowerCase();

            if(!fileTag.startsWith( "material" )){
                continue;
            }
            List<MultipartFile > fileList = entry.getValue();
            if(null == fileList || fileList.isEmpty()){
                continue;
            }
            for (MultipartFile file:fileList ) {
                String fileName = file.getOriginalFilename();

                BASE64Decoder decoder = new BASE64Decoder();
                fileName = new String(decoder.decodeBuffer(fileName),"UTF-8");
                String path = EditAffairUtil.getMaterialPath(affairCode,fileName,filebasePath);
                // 存放文件的绝对路径
                DataOutputStream out1 = new DataOutputStream(new FileOutputStream(path));
                // 附件输入流
                InputStream is1 = null;
                is1 = file.getInputStream();
                byte[] buf = new byte[1024];
                int len1 = 0;
                while ((len1 = is1.read(buf)) > 0) {
                    out1.write(buf, 0, len1);
                }
                is1.close();
                out1.close();
            }
        }
    }

    /**
     * 存放文件
     * @param affairCode
     * @param materialName
     * @return
     */
    private static String getMaterialPath(String affairCode,String materialName,String  path){
        //文件根目录
        logger.info( "目标文件路径:"+path +"  "+  materialName);
        String[] materialAndFile = materialName.split( "_" );
        String realPathDir = path
                + File.separator + "material"
                + File.separator + affairCode
                + File.separator + materialAndFile[0];
        File dirFile = new File(realPathDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        String realPath = realPathDir + File.separator + materialAndFile[1];
        logger.info( "文件路径:"+realPath );
        return realPath;
    }

    /**
     * 构建附件信息
     * @param actCookie
     * @param affairId
     * @return
     * @throws IOException
     */
    private static List<JSONObject> listAffairMaterial(String actCookie, String affairId) throws IOException {

        String url = "http://"+SysConst.DOMAIN+"/dothingsui/affairMaterial/listData";
        Map<String,String> searchParam = new HashMap<>( );
        searchParam.put( "affairId", affairId);
        searchParam.put( "page","1" );
        searchParam.put( "rows","10" );
        searchParam.put( "_", System.currentTimeMillis()+"" );

        String responeBody = WestarHttpUtil.getMethod(url,actCookie,searchParam);
        if(StringUtils.isEmpty( responeBody)){
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(responeBody);
        Integer total = jsonObject.getInteger("total");

        List<JSONObject> result = new ArrayList<>(  );
        if(total > 0){
            JSONArray rows = jsonObject.getJSONArray("rows");
            for (Object row: rows) {
                result.add(JSONObject.parseObject(row.toString()));
            }

            //总页数
            Integer totalPageNum = total/10;
            if(total % 10 > 0){
                totalPageNum += 1;
            }

            for(int i=2;i<=totalPageNum;i++){
                searchParam.put( "page",i+ "" );
                searchParam.put( "_", System.currentTimeMillis()+"" );
                responeBody = WestarHttpUtil.getMethod(url,actCookie,searchParam);
                if(StringUtils.isEmpty( responeBody)){
                    continue;
                }
                rows = jsonObject.getJSONArray("rows");
                for (Object row: rows) {
                    result.add(JSONObject.parseObject(row.toString()));
                }
            }

        }
        return result;


    }

    /**
     * 资料上传
     * @param actCookie 认证标识
     * @param affairId 办件主键
     * @param idForStr 材料主键
     * @param materialName 材料附件
     * @param esheet 也买你已有参数
     */
    private static void showUploadMaterial(String actCookie,
                                           String affairId,
                                           String idForStr,
                                           String materialName,
                                           Map<String, String> esheet,
                                           String affairCode,String path,
                                           String version) throws IOException {

        String dirName = null;
        if(StringUtils.isEmpty( materialName ) || materialName.indexOf( "." ) < 0 ){
            return;
        }

        dirName = materialName.trim().substring( materialName.indexOf( "." ) + 1 );

        String realPathDir = path
                + File.separator + "material"
                + File.separator + affairCode
                + File.separator + dirName;
        File dirFile = new File(realPathDir);
        if(!dirFile.exists()){
            return;
        }

        List<FilePart> partFileList = new ArrayList<>(  );
        File[] files = dirFile.listFiles();
        if(files.length > 0){
            for (File file :files ) {
                String fileName = file.getName();
                CustomFilePart filePart = new CustomFilePart("upFile", fileName ,file);
                partFileList.add(filePart);
            }
        }
        //从页面构建表单参数
        Map<String,String> affairMaterialUploadParam = EditAffairUtil.constrAffairMaterialUploadParam(actCookie,affairId,esheet,version);
        //参数补充
        affairMaterialUploadParam.put("materialName",materialName);
        affairMaterialUploadParam.put("materialId",idForStr  );
        affairMaterialUploadParam.put("busiId",idForStr  );


        String url = "http://"+SysConst.DOMAIN+"/dothingsui/attachment/importMultiFile";
        String responeBody = WestarHttpUtil.postMethodWithFiles(url,actCookie,affairMaterialUploadParam, partFileList );

        JSONObject jsonObject = JSONObject.parseObject(responeBody);
        if(jsonObject.getBoolean( "success" )){
            JSONArray rows = jsonObject.getJSONArray("rows");
            for (Object obj : rows) {
                String attachmentsId = JSONObject.parseObject(obj.toString()).getString( "id" );
                String fileName = JSONObject.parseObject(obj.toString()).getString( "fileName" );
                if(version.equals("1")){
                    //新增办件应交材料明细
                    EditAffairUtil.addAffairMaterialDetailV3(actCookie,attachmentsId,fileName,affairMaterialUploadParam);
                }else{
                    //新增办件应交材料明细
                    EditAffairUtil.addAffairMaterialItem(actCookie,attachmentsId,fileName,affairMaterialUploadParam);
                }

            }
        }
    }

    /**
     * 新增办件应交材料明细
     * @param actCookie
     * @param attachmentsId
     * @param fileName
     * @param affairMaterialUploadParam
     */
    private static void addAffairMaterialItem(String actCookie,
                                              String attachmentsId,
                                              String fileName,
                                              Map<String, String> affairMaterialUploadParam) throws IOException {
        String materialId = affairMaterialUploadParam.get("materialId" );

        String url = "http://"+SysConst.DOMAIN+"/dothingsui/affairMaterialItem/save";
        Map<String,String> postParam = new HashMap<>(  );
        postParam.put( "materialId",materialId );
        postParam.put( "attachmentsId",attachmentsId );
        postParam.put( "fileName",fileName );
        postParam.put( "licenseId","" );

        WestarHttpUtil.postMethod( url,actCookie,postParam );

    }
    /**
     * 新增办件应交材料明细
     * @param actCookie
     * @param attachmentsId
     * @param fileName
     * @param affairMaterialUploadParam
     */
    private static void addAffairMaterialDetailV3(String actCookie,
                                              String attachmentsId,
                                              String fileName,
                                              Map<String, String> affairMaterialUploadParam) throws IOException {
        String materialId = affairMaterialUploadParam.get("busiId" );

        String url = "http://"+SysConst.DOMAIN+"/dothingsui/affairMaterialV3/saveDetails";

        JSONObject itemDetails = new JSONObject();
        itemDetails.put( "attachmentId",attachmentsId );
        itemDetails.put( "fileName",fileName );

        Map<String,String> postParam = new HashMap<>(  );
        postParam.put( "id",materialId );
        postParam.put( "itemDetails",itemDetails.toJSONString() );

        WestarHttpUtil.postMethod( url,actCookie,postParam );

    }

    /**
     * 获取表单提交数据
     * @param actCookie
     * @param affairId
     * @param esheet
     * @return
     */
    private static Map<String, String> constrAffairMaterialUploadParam(
            String actCookie,String affairId,Map<String, String> esheet,
            String version) throws IOException {
        String applicantIdCard = esheet.get("applicantIdCard");
        String applicantName = esheet.get("applicantName");

        String url = "http://"+SysConst.DOMAIN+"/dothingsui/affairMaterial/upload/" + affairId+"?1=1";
        if(version.equals("1")){
            url = "http://"+SysConst.DOMAIN+"/dothingsui/affairMaterialV3/upload/" + affairId+"?version=1";
        }
        Map<String,String> searchParam = new HashMap<>(  );
        if(StringUtils.isNotEmpty( applicantIdCard )){
            searchParam.put("applicantIdCard",applicantIdCard);
        }
        if(StringUtils.isNotEmpty( applicantName )){
            searchParam.put("applicantName",applicantName);
        }
        String responeBody = WestarHttpUtil.getMethod( url,actCookie,searchParam );


        Map<String,String> affairMaterialUploadParam = new HashMap<>();

        Document doc = Jsoup.parse(responeBody);
        Elements eleForm = doc.select("#upload_form");

        String busiAlias = eleForm.select( "#busiAlias" ).attr( "value" );
        String areaCode = eleForm.select( "#areaCode" ).attr( "value" );
        String busiId = eleForm.select( "#busiId" ).attr( "value" );
        String materialId = eleForm.select( "#materialId" ).attr( "value" );
        String materialName = eleForm.select( "#materialName" ).attr( "value" );
        String categoryCode = eleForm.select( "#categoryCode" ).attr( "value" );

        affairMaterialUploadParam.put("applicantIdCard",applicantIdCard  );
        affairMaterialUploadParam.put("busiAlias",busiAlias  );
        affairMaterialUploadParam.put("areaCode",areaCode  );
        affairMaterialUploadParam.put("busiId",busiId  );
        affairMaterialUploadParam.put("version",version  );
        affairMaterialUploadParam.put("materialId",materialId  );
        affairMaterialUploadParam.put("materialName",materialName  );
        affairMaterialUploadParam.put("categoryCode",categoryCode  );
        return affairMaterialUploadParam;

    }


}
